<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\helpers\VarDumper;
use yii\helpers\ArrayHelper;

use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;

use app\models\RecordsModel;

class RecordsController extends Controller
{

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }
    public function actionAdd()
    {
        $openid = Yii::$app->request->post('openid');
        $code = Yii::$app->request->post('code');
        $examname = Yii::$app->request->post('examname');
 
        // Yii::$app->db->createCommand()->insert('message',[
        //     'image'=>$image,
        //     'title'=>$title,
        //     'content'=>$content
        //     ])->execute();

        $total = RecordsModel::find()
        ->where(['openid' => $openid,'code' => $code])
        ->count();
        if($total==0){
            // 新建一条记录
            $model = new RecordsModel;
            $model->openid = $openid;
            $model->code = $code;
            $model->examname = $examname;

            $model->save();

            $id =$model->id;
            $model = RecordsModel::find()
                ->where(['id' => $id])
                ->orderBy('id DESC')
                ->asArray()
                ->one();

            $data = array(
                'code' => 0,
                'message' => '新增成功',
                'result' => $model
            );
        }else{
            $data = array(
                'code' => 0,
                'message' => '已经存在',
                'result' => date("Y-m-d H:i:s",time())
            );
        }
        
        $json = json_encode($data);
        return $json;
    }
    public function actionGetitems()
    {
        $model = RecordsModel::find()
            ->asArray()
            ->all();

        $json = json_encode($model);
        return $json;
    }
    public function actionGetbyopenid()
    {
        $openid = Yii::$app->request->post('openid');
        $model = RecordsModel::find()
            ->where(['openid' => $openid])
            ->orderBy('id DESC')
            ->asArray()
            ->all();

        $data = array(
            'code' => 0,
            'message' => '',
            'result' => $model
        );

        $json = json_encode($data);
        return $json;
    }
}
